<script>
import mammoth from "mammoth";
import XLSX from 'xlsx'
import {getHomeworkDetail} from "../../api/apiz";

export default {
  name: "filework",
  data() {
    return {
      detailData: {},
      vHtml: '',
      isPdf: false,
      iframeLoading: false,
      isExcel: false,
      ifexecelLoading: false,
      isWord: false,
      ifwordsLoading: false,
      isImgs: false,
      excelData: []
    }
  },
  methods: {
    getDetail(studentId, taskOriginId) {
      let params = {
        studentId: studentId,
        taskOriginId: taskOriginId
      }
      getHomeworkDetail(params).then(res => {
        if (res.code == 200) {
          this.detailData = res.result
          if (res.result.answerFileUrl.includes('.pdf') || res.result.answerFileUrl.includes('.txt')) {
            let websurl = this.$httpFile + this.detailData.answerFileUrl
            this.previewFnPDF(websurl)
            return
          }
          if (res.result.answerFileUrl.includes('.xls') || res.result.answerFileUrl.includes('.xlsx')) {
            this.previewFnExecl(this.$httpFile + this.detailData.answerFileUrl)
            return
          }
          if (res.result.answerFileUrl.includes('.doc') || res.result.answerFileUrl.includes('.docx')) {
            let websurl = this.$httpFile + this.detailData.answerFileUrl
            this.readExcelFromRemoteFile(websurl)
            return
          }
          if (res.result.answerFileUrl.includes('.jpg') || res.result.answerFileUrl.includes('.png') || res.result.answerFileUrl.includes('.jpeg')) {
            this.isPdf = false
            this.isExcel = false
            this.isWord = false
            this.vHtml = this.$httpFile + this.detailData.answerFileUrl
            return
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // word
    readExcelFromRemoteFile(url) {
      var vm = this;
      this.isWord = true
      this.isExcel = false
      this.isPdf = false
      var xhr = new XMLHttpRequest();
      xhr.open("get", url, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function () {
        if (xhr.status == 200) {
          mammoth.convertToHtml({arrayBuffer: new Uint8Array(xhr.response)}).then(function (resultObject) {
            vm.$nextTick(() => {
              vm.vHtml = resultObject.value;
            });
          });
        }
      };
      xhr.send();
    },
    //   表格
    previewFnExecl(url) {
      this.isExcel = true
      this.isWord = false
      this.isPdf = false
      downloadFileByUniq2(encodeURIComponent(url)).then(data => {
        const workbook = XLSX.read(new Uint8Array(data), {type: 'array'}) // 解析数据
        var worksheet = workbook.Sheets[workbook.SheetNames[0]] // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
        // this.excelHtml = XLSX.utils.sheet_to_html(worksheet) // 渲染成html
        const sheet2JSONOpts = {
          /** Default value for null/undefined values */
          defval: ''// 给defval赋值为空的字符串,不然没值的这列就不显示
        }
        // 渲染成json
        this.excelData = XLSX.utils.sheet_to_json(worksheet, sheet2JSONOpts)
        console.log(this.excelData)
      })
    },
    //   pdf
    previewFnPDF(url) {
      this.isPdf = true
      this.isExcel = false
      this.isWord = false
      this.vHtml = ''
      this.iframeLoading = true
      downloadFileByUniq(encodeURIComponent(url)).then(res => {
        const blob = new Blob([res], {type: item.url.includes('.pdf') ? 'application/pdf;' : ''})
        const href = window.URL.createObjectURL(blob)
        this.vHtml = href
      }).finally(() => {
        this.iframeLoading = false
      })
    },
  }
}
</script>

<template>
  <div>
    <div class="filework_Title">学生作业内容</div>
    <!--word-->
    <div class="filework_view" v-if="isWord" >
      <div id="wordView" v-html="vHtml"></div>
    </div>
    <!--  pdf-->
    <div v-if="isPdf" v-loading="iframeLoading" class="filework_view">
      <iframe :src="vHtml" type="application/x-google-chrome-pdf"/>
    </div>
    <div v-else-if="isExcel">
      <el-table
          :data="excelData"
          border
          stripe
          :header-cell-style="{'background':'#F5F4F7'}"
      >
        <el-table-column
            type="index"
            label="序号"
            width="60"
            :resizable="false"
            align="center"
        />
        <el-table-column
            v-for="(value, key, index) in excelData[0]"
            :key="index"
            :prop="key"
            :label="key"
        />
      </el-table>
    </div>
    <div v-else class="imgfile">
      <img :src="vHtml" style="width: 100%" alt="">
    </div>

  </div>
</template>

<style scoped lang="less">
.filework_Title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
}

.filework_view {
  border: 2px dotted #e8e8e8;
  padding: 6px 10px;
  border-radius: 5px;
  height: calc(100vh - 240px);
  //background-color: #f5f5f5;
}

#wordView {
  letter-spacing: 2px;
}
</style>
